package de.rj.urwalking.tasks;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.AsyncTask;
import android.widget.TextView;

//AsyncTask encapsulating the reverse-geocoding API.  Since the geocoder API is blocked,
//we do not want to invoke it from the UI thread.

public class ReverseGeocodingTask extends AsyncTask<Location, Void, String> {

	private Context mContext;
	private TextView mLocationTextView;

	public ReverseGeocodingTask(Context context, TextView locationTextView) {
		mContext = context;
		mLocationTextView = locationTextView;
	}

	@Override
	protected String doInBackground(Location... params) {
		Geocoder geocoder = new Geocoder(mContext, Locale.getDefault());

		Location loc = params[0];
		List<Address> addresses = null;
		try {
			// Call the synchronous getFromLocation() method by passing in the lat/long values.
			addresses = geocoder.getFromLocation(loc.getLatitude(), loc.getLongitude(), 1);
		} catch (IOException e) {
			e.printStackTrace();
			// Return empty string if we got an error.
			return "";
		}
		if (addresses != null && addresses.size() > 0) {
			Address address = addresses.get(0);
			// Format the first line of address (if available), city, and country name.
			String addressText = address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "";
			// Update the UI via a message handler.
			return addressText;
		}
		return "";
	}

	@Override
	protected void onPostExecute(String result) {
		super.onPostExecute(result);
		mLocationTextView.setText(result);
	}

}
